<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>考试管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleCreate">创建考试</el-button>
      </div>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" size="small">
        <el-form-item label="学科">
          <el-select v-model="queryParams.subjectId" placeholder="请选择学科" clearable filterable>
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="教育阶段">
          <el-select v-model="queryParams.educationLevel" placeholder="请选择教育阶段" clearable @change="handleEducationLevelChange">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" :value="0"></el-option>
            <el-option label="进行中" :value="1"></el-option>
            <el-option label="已结束" :value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学校">
          <el-select v-model="queryParams.schoolId" placeholder="请选择学校" clearable filterable>
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="examList"
        style="width: 100%"
        border
      >
        <el-table-column
          type="index"
          label="#"
          width="50"
          align="center">
        </el-table-column>
        
        <el-table-column
          prop="title"
          label="考试标题"
          min-width="200">
        </el-table-column>
        
        <el-table-column
          prop="paperTitle"
          label="试卷"
          min-width="150">
        </el-table-column>
        
        <el-table-column
          prop="subjectName"
          label="学科"
          width="100"
          align="center">
        </el-table-column>
        
        <el-table-column
          prop="educationLevelName"
          label="教育阶段"
          width="100"
          align="center">
        </el-table-column>
        
        <el-table-column
          prop="schoolName"
          label="学校"
          width="120"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.schoolName || '所有学校' }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="考试时间"
          width="260"
          align="center">
          <template slot-scope="scope">
            <div>开始：{{ formatDateTime(scope.row.startTime) }}</div>
            <div>结束：{{ formatDateTime(scope.row.endTime) }}</div>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="statusName"
          label="状态"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作"
          width="180"
          align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleDetail(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-if="scope.row.status === 0"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              class="delete-btn"
              @click="handleDelete(scope.row)"
              v-if="scope.row.status === 0"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getExamList, deleteExam, updateExamStatus } from '@/api/exam';
import { getAllSubjects } from '@/api/subject';
import { getSchoolList } from '@/api/school';

export default {
  name: 'ExamList',
  data() {
    return {
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        subjectId: undefined,
        educationLevel: undefined,
        status: undefined,
        schoolId: undefined,
        keyword: ''
      },
      // 考试列表
      examList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 学科选项
      subjectOptions: [],
      // 所有学科
      allSubjects: [],
      // 学校选项
      schoolOptions: []
    };
  },
  created() {
    this.getSubjects();
    this.getSchools();
    this.getList();
    // 定期更新考试状态
    this.updateStatus();
    this.statusTimer = setInterval(() => {
      this.updateStatus();
    }, 60000); // 每分钟更新一次
  },
  beforeDestroy() {
    // 清除定时器
    if (this.statusTimer) {
      clearInterval(this.statusTimer);
    }
  },
  methods: {
    // 获取学科列表
    getSubjects() {
      getAllSubjects().then(response => {
        this.allSubjects = response.data;
        this.filterSubjectsByLevel(this.queryParams.educationLevel);
      });
    },
    // 获取学校列表
    getSchools() {
      getSchoolList(1, 100).then(response => {
        this.schoolOptions = response.data.records.map(school => ({
          value: school.id,
          label: school.name
        }));
      });
    },
    // 根据教育阶段筛选学科
    filterSubjectsByLevel(level) {
      if (!level || !this.allSubjects || this.allSubjects.length === 0) {
        this.subjectOptions = this.allSubjects.map(subject => ({
          value: subject.id,
          label: subject.name
        }));
        return;
      }
      
      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
      
      // 如果当前选中的学科不在筛选结果中，清空选择
      if (this.queryParams.subjectId) {
        const exists = filteredSubjects.some(subject => subject.id === this.queryParams.subjectId);
        if (!exists) {
          this.queryParams.subjectId = undefined;
        }
      }
    },
    // 教育阶段变化时触发
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
    },
    // 获取考试列表
    getList() {
      this.loading = true;
      getExamList(this.queryParams).then(response => {
        this.examList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 更新考试状态
    updateStatus() {
      updateExamStatus().then(() => {
        // 如果当前页面显示的是考试列表，则刷新数据
        if (this.$route.path === '/exams') {
          this.getList();
        }
      });
    },
    // 查询按钮点击事件
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 重置按钮点击事件
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        subjectId: undefined,
        educationLevel: undefined,
        status: undefined,
        schoolId: undefined,
        keyword: ''
      };
      this.getList();
    },
    // 每页条数改变时触发
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.getList();
    },
    // 当前页改变时触发
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getList();
    },
    // 创建考试
    handleCreate() {
      this.$router.push('/exam/create');
    },
    // 查看考试详情
    handleDetail(row) {
      this.$router.push(`/exam/detail/${row.id}`);
    },
    // 编辑考试
    handleUpdate(row) {
      this.$router.push(`/exam/edit/${row.id}`);
    },
    // 删除考试
    handleDelete(row) {
      this.$confirm('确定要删除该考试吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteExam(row.id).then(() => {
          this.$message.success('删除成功');
          this.getList();
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 获取状态标签类型
    getStatusType(status) {
      switch (status) {
        case 0: return 'info';
        case 1: return 'success';
        case 2: return 'warning';
        default: return '';
      }
    }
  }
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.delete-btn {
  color: #F56C6C;
}
</style> 